package com.uzai.console.service.tb.tbtokennew.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.tb.tbtokennew.*;
import com.uzai.console.entity.TbTokenNew;
import com.uzai.console.mapper.TbTokenNewMapper;
import com.uzai.console.service.tb.tbtokennew.TbTokenNewService;
import com.uzai.console.vo.tb.tbtokennew.TbTokenNewAuthUrlVo;
import com.uzai.console.vo.tb.tbtokennew.TbTokenNewInfoVo;
import com.uzai.console.vo.tb.tbtokennew.TbTokenNewPageVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/***
* 运营商基本配置
* @author liuqi
* @date 2021年08月13日 11:34
*/
@Service
public class TbTokenNewServiceImpl implements TbTokenNewService {

   Logger logger = LoggerFactory.getLogger(TbTokenNewServiceImpl.class);

   @Autowired
   private TbTokenNewMapper tbTokenNewMapper;

   @Autowired
   private RedisTemplate redisTemplate;
   @Autowired
   private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
    * 查询淘宝联盟列表
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenNewQuery
    * @return null
    */
   public Page<TbTokenNewPageVo> findTbTokenNewList(TbTokenNewQuery tbTokenNewQuery){
       Integer now = DateUtil.getNowTime();

       //新建返回到页面的LIST对象
       List<TbTokenNewPageVo> tbTokenNewPageVoList = new ArrayList<>();

       //执行分页查询对象
       Page<TbTokenNew> page = new Page<>();
       tbTokenNewQuery.convert(page);
       ArrayList<TbTokenNew> tbOrderList =  tbTokenNewMapper.findByList(page, tbTokenNewQuery);
       if(tbOrderList != null && tbOrderList.size() > 0){
           for (TbTokenNew tbTokenNew : tbOrderList){
               TbTokenNewPageVo tbTokenNewPageVo = new TbTokenNewPageVo();
               BeanUtils.copyProperties(tbTokenNew, tbTokenNewPageVo);
               if(StringUtils.isNotBlank(tbTokenNew.getPids())){
                   tbTokenNewPageVo.setPidList(JSONObject.parseArray(tbTokenNew.getPids(), String.class));
               }

               //到期时间
               Integer expiretime = Tools.getInteger(tbTokenNew.getExptime());
               if(expiretime.intValue() <= now.intValue()){
                   tbTokenNewPageVo.setExpireStatus(0);  //已到期
               }else if(expiretime.intValue() > now && expiretime.intValue() <= now + 7*24*3600){
                   tbTokenNewPageVo.setExpireStatus(2);  //即将到期
               }else{
                   tbTokenNewPageVo.setExpireStatus(1);  //未到期
               }

               tbTokenNewPageVoList.add(tbTokenNewPageVo);
           }
       }

       //返回到页面分页对象
       Page<TbTokenNewPageVo> pageVo = new Page<>();
       BeanUtils.copyProperties(page, pageVo);
       pageVo.setRecords(tbTokenNewPageVoList);
       //将分页信息复制到返回到页面的分页MO当中
       return pageVo;
   }


    /**
    * 设置炮灰
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenNewSetPhDto
    * @return null
    */
   public void setPh(TbTokenNewSetPhDto tbTokenNewSetPhDto){
       if(tbTokenNewSetPhDto.getId() == null || tbTokenNewSetPhDto.getIsPh() == null || tbTokenNewSetPhDto.getPhOrderCount() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
       }

       TbTokenNew tbTokenNew = tbTokenNewMapper.selectById(tbTokenNewSetPhDto.getId(), tbTokenNewSetPhDto.getMerId());

       if(tbTokenNew == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝联盟账号不存在");
       }

       tbTokenNew.setPhOrderCount(tbTokenNewSetPhDto.getPhOrderCount());
       tbTokenNew.setIsPh(tbTokenNewSetPhDto.getIsPh());
       //启动炮灰，需要将辅助关闭
       if(tbTokenNewSetPhDto.getIsPh().intValue() == 1){
           tbTokenNew.setIsAux(0);
       }

       tbTokenNewMapper.update(tbTokenNew);

   }

    /**
    * 设置辅助账号
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenNewSetAuxDto
    * @return null
    */
   public void setAux(TbTokenNewSetAuxDto tbTokenNewSetAuxDto){
       if(tbTokenNewSetAuxDto.getId() == null || tbTokenNewSetAuxDto.getIsAux() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
       }
       TbTokenNew tbTokenNew = tbTokenNewMapper.selectById(tbTokenNewSetAuxDto.getId(), tbTokenNewSetAuxDto.getMerId());
       if(tbTokenNew == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝联盟账号不存在");
       }
       tbTokenNew.setIsAux(tbTokenNewSetAuxDto.getIsAux());
       //启动辅助，需要将炮灰关闭
       if(tbTokenNewSetAuxDto.getIsAux().intValue() == 1){
           tbTokenNew.setIsPh(0);
       }
       tbTokenNewMapper.update(tbTokenNew);

   }

    /***
    * 添加授权
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param merId
    * @return null
    */
   public TbTokenNewAuthUrlVo addTbTokenNew(Long merId){
       //刷新授权的链接，将运营商ID放入自定义参数state当中，授权刷新之后，淘宝调用回调函数返回授权信息
       //淘宝联盟
       String merId_type =  "v3" + merId + "_0";
       String url =  uzaiConsoleSysConfig.getTbTokenNewAuthorize() + merId_type;
       TbTokenNewAuthUrlVo tbTokenNewAuthUrlVo = new  TbTokenNewAuthUrlVo();
       tbTokenNewAuthUrlVo.setUrl(url);
       return tbTokenNewAuthUrlVo;
   }

    /***
    * 查询联盟详情
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenNewIdDto
    * @return null
    */
   public TbTokenNewInfoVo findTbTokenNewInfo(TbTokenNewIdDto tbTokenNewIdDto){

       if(tbTokenNewIdDto.getId() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
       }
       TbTokenNew tbTokenNew = tbTokenNewMapper.selectById(tbTokenNewIdDto.getId(), tbTokenNewIdDto.getMerId());
       if(tbTokenNew == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝联盟账号不存在");
       }

       //返回页面对象
       TbTokenNewInfoVo tbTokenNewInfoVo = new TbTokenNewInfoVo();
       //将查询到的对象复制给返回页面对象
       BeanUtils.copyProperties(tbTokenNew, tbTokenNewInfoVo);

       if(StringUtils.isNotBlank(tbTokenNew.getPids())){
           tbTokenNewInfoVo.setPidList(JSONObject.parseArray(tbTokenNew.getPids(), String.class));
       }

       return tbTokenNewInfoVo;
   }

    /***
    * 修改联盟PID
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenNewUpdatePidDto
    * @return null
    */
   public void updatePid(TbTokenNewUpdatePidDto tbTokenNewUpdatePidDto){

       if(tbTokenNewUpdatePidDto.getId() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
       }

       if(tbTokenNewUpdatePidDto.getSettleType() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "比价订单行为未选择方式");
       }

       if(StringUtils.isBlank(tbTokenNewUpdatePidDto.getDefPid())){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请设置默认PID");
       }

       TbTokenNew tbTokenNew = tbTokenNewMapper.selectById(tbTokenNewUpdatePidDto.getId(), tbTokenNewUpdatePidDto.getMerId());
       if(tbTokenNew == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝联盟账号不存在");
       }

       tbTokenNew.setSettleType(tbTokenNewUpdatePidDto.getSettleType());
       tbTokenNew.setDefPid(tbTokenNewUpdatePidDto.getDefPid());
       tbTokenNew.setPids(JSONObject.toJSONString(tbTokenNewUpdatePidDto.getPidList()));
       tbTokenNew.setPidWlist(tbTokenNewUpdatePidDto.getPidWlist());
       tbTokenNewMapper.update(tbTokenNew);

       //设置redis
       //先删除pid队列
       redisTemplate.delete(String.format(RedisCacheKeyEnum.TB_PIDS_QUEUE.getKey(), tbTokenNew.getMerId(), tbTokenNew.getUserId()));
       //把pidList添加redis队列当中
       List<String> pidList = tbTokenNewUpdatePidDto.getPidList();
       if(pidList != null && pidList.size() > 0){
           for (String pid : pidList){
               redisTemplate.opsForList().leftPushAll(String.format(RedisCacheKeyEnum.TB_PIDS_QUEUE.getKey(), tbTokenNew.getMerId(), tbTokenNew.getUserId()), pid);
           }
       }
   }

    /***
    * 设置是否同步订单
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenNewIsSyncOrderDto
    * @return null
    */
   public void setIsSyncOrder(TbTokenNewIsSyncOrderDto tbTokenNewIsSyncOrderDto){
       if(tbTokenNewIsSyncOrderDto.getId() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
       }

       TbTokenNew tbTokenNew = tbTokenNewMapper.selectById(tbTokenNewIsSyncOrderDto.getId(), tbTokenNewIsSyncOrderDto.getMerId());

       if(tbTokenNew == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此联盟不存在");
       }

       tbTokenNew.setIsSyncOrder(tbTokenNewIsSyncOrderDto.getIsSyncOrder());

       tbTokenNewMapper.update(tbTokenNew);
   }

    /***
    * 删除
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenNewIdDto
    * @return null
    */
   public void deleteTbTokenNew(TbTokenNewIdDto tbTokenNewIdDto){
       if(tbTokenNewIdDto.getId() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
       }

       TbTokenNew tbTokenNew = tbTokenNewMapper.selectById(tbTokenNewIdDto.getId(), tbTokenNewIdDto.getMerId());
       if(tbTokenNew != null){

           if(tbTokenNew.getType().intValue() == 2){ //淘宝和饿了么共享联盟
               tbTokenNew.setType(1); //修改成饿了么独享联盟
               tbTokenNewMapper.updateSelective(tbTokenNew);
           }else{
               tbTokenNewMapper.deleteById(tbTokenNewIdDto.getId(), tbTokenNewIdDto.getMerId());
               //删除redis
               redisTemplate.delete(String.format(RedisCacheKeyEnum.TB_PIDS_QUEUE.getKey(), tbTokenNew.getMerId(), tbTokenNew.getUserId()));
           }
       }

   }

}
